package com.cne.gmail.Gmail.Handle;


import com.cne.gmail.Gmail.model.MailSenderInfo;
import com.cne.gmail.Gmail.model.UserModel;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import com.google.api.services.plus.Plus;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Properties;

public class GmailHandle {
    private static final String APPLICATION_NAME = "Gmail";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    private static Credential getCredentials(NetHttpTransport httpTransport, UserModel user) throws IOException {
        InputStream in = GmailHandle.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
        return new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY)
                .setClientSecrets(clientSecrets)
                .build()
                .setExpiresInSeconds(Long.valueOf(26784000))
                .setAccessToken(user.getAccessToken())
                .setRefreshToken(user.getRefreshToken()
                );
    }

    public static Gmail service (UserModel user) throws IOException, GeneralSecurityException {
        final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        Credential credential = getCredentials(httpTransport,user);
        return new Gmail.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    //获取用户信息
    public static Plus userInfo( UserModel user) throws GeneralSecurityException, IOException {
        final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        Credential credential = getCredentials(httpTransport,user);
        Plus plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
        return plus;
    }

    //业务拆分1.MimeMessage
    public static Message createMessageWithEmail(MimeMessage emailContent)
            throws MessagingException, IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        emailContent.writeTo(buffer);
        byte[] bytes = buffer.toByteArray();
        String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
    }
    //业务拆分1.对于发件人的处理，2.对于收件人的处理3.对于主题的处理4.对于消息的处理5.对于附件的处理
    public static MimeMessage createEmailWithAttachment(MailSenderInfo messageInfo)
            throws Exception {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage email = new MimeMessage(session);
        String from=  messageInfo.getFrom();
        List<String> tos=messageInfo.getReceivers();
        List<String> ccs=messageInfo.getCc();
        String subject=messageInfo.getSubject();
        String bodyText=messageInfo.getContent();
        //发件人
        email.setFrom(new InternetAddress(from));
        //收件人和抄送人处理
        MessageHander.ToandCc(tos,ccs,email);
        //主题文字
        email.setSubject(subject);
        // 将邮件中各个部分组合到一个"mixed"型的 MimeMultipart 对象
        MimeMultipart multipart = new MimeMultipart("mixed");
        //处理邮件正文部分
        MessageHander.createContent(bodyText, messageInfo.getContextImgModels(),multipart);
        //处理附件部分
        MessageHander.attchHandler(messageInfo.getAttchmentModels(),multipart);
        email.setContent(multipart);
        return email;

    }

}